﻿using YNTK.Common.Core.Manager;
using YNTK.Common.Enum;
using YNTK.Common.Extension;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.SubDev.Interfaces.ZyOaArticle;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YNTK.SubDev.Entitys;
using YNTK.SubDev.Entitys.Dto.ZyOaArticle;
using Yitter.IdGenerator;
using YNTK.Common.Helper;
using YNTK.JsonSerialization;

namespace YNTK.SubDev.ZyOaArticle
{
    /// <summary>
    /// zy_oa_article服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "SubDev",Name = "ZyOaArticle", Order = 200)]
    [Route("api/SubDev/[controller]")]
    public class ZyOaArticleService : IZyOaArticleService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ZyOaArticleEntity> _zyOaArticleRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ZyOaArticleService"/>类型的新实例
        /// </summary>
        public ZyOaArticleService(
            ISqlSugarRepository<ZyOaArticleEntity> zyOaArticleRepository,
            IUserManager userManager)
        {
            _zyOaArticleRepository = zyOaArticleRepository;            
            _db = _zyOaArticleRepository.Context;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取zy_oa_article
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ZyOaArticleEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ZyOaArticleInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取zy_oa_article列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ZyOaArticleListQueryInput input)
        {
            var sidx = input.sidx == null ? "createTime" : input.sidx;
            var data = await _db.Queryable<ZyOaArticleEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.categoryId), p => p.CategoryId.Equals(input.categoryId))
                .WhereIF(!string.IsNullOrEmpty(input.title), p => p.Title.Contains(input.title))
                .Select(it=> new 
                {
                    id = it.Id,
                    categoryId=it.CategoryId,
                    title=it.Title,
                    creater=it.Creater,
                    createTime=it.CreateTime,
                    isType=it.IsType,
                }).MergeTable().Select<ZyOaArticleListOutput>().OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return TkPageResult<ZyOaArticleListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建zy_oa_article
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ZyOaArticleCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<ZyOaArticleEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.Creater = _userManager.UserId;
            entity.CreateTime = DateTime.Now;  
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
        /// 批量删除zy_oa_article
        /// </summary>
        /// <param name="ids">主键数组</param>
        /// <returns></returns>
        [HttpPost("batchRemove")]
        public async Task BatchRemove([FromBody] List<string> ids)
        {
            var entitys = await _db.Queryable<ZyOaArticleEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                try
                {
                    //开启事务
                    _db.Ado.BeginTran();
                    //批量删除zy_oa_article
                    await _db.Deleteable<ZyOaArticleEntity>().In(d => d.Id,ids).ExecuteCommandAsync();
                    //关闭事务
                    _db.Ado.CommitTran();
                }
                catch (Exception)
                {
                    //回滚事务
                    _db.Ado.RollbackTran();
                    throw YNTKException.Oh(ErrorCode.COM1002);
                }
            }
        }

        /// <summary>
        /// 更新zy_oa_article
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ZyOaArticleUpInput input)
        {
            var entity = input.Adapt<ZyOaArticleEntity>();
            entity.LastModifyTime = DateTime.Now;  
            entity.LastModifyUserId = _userManager.UserId;
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除zy_oa_article
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<ZyOaArticleEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw YNTKException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<ZyOaArticleEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1002);
        }
    }
}
